'    Copyright 2008 Jan Molnar <jan.molnar@abds.de>
'
'    This file is part of JCQ.

'    JCQ is free software: you can redistribute it and/or modify
'    it under the terms of the GNU General Public License as published by
'    the Free Software Foundation, either version 2 of the License, or
'    (at your option) any later version.

'    JCQ is distributed in the hope that it will be useful,
'    but WITHOUT ANY WARRANTY; without even the implied warranty of
'    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'    GNU General Public License for more details.

'    You should have received a copy of the GNU General Public License
'    along with JCQ. If not, see <http://www.gnu.org/licenses/>.

Public Class Flap
    Implements ISerializable

    Private _DataSize As Integer

    Public Const SizeFixPart As Integer = 6

    Public Sub New()

    End Sub

    Public Sub New(ByVal channel As FlapChannel)
        _Channel = channel
    End Sub

    Private _Channel As FlapChannel
    Public Property Channel() As FlapChannel
        Get
            Return _Channel
        End Get
        Set(ByVal value As FlapChannel)
            _Channel = value
        End Set
    End Property

    Private _DatagramSequenceNumber As Integer
    Public Property DatagramSequenceNumber() As Integer
        Get
            Return _DatagramSequenceNumber
        End Get
        Set(ByVal value As Integer)
            _DatagramSequenceNumber = value
        End Set
    End Property

    Private _DataItems As New List(Of ISerializable)
    Public ReadOnly Property DataItems() As List(Of ISerializable)
        Get
            Return _DataItems
        End Get
    End Property

    Private _HasData As Boolean = False

    Public ReadOnly Property HasData() As Boolean Implements ISerializable.HasData
        Get
            Return _HasData
        End Get
    End Property

    Public Overridable Function CalculateDataSize() As Integer Implements ISerializable.CalculateDataSize
        Dim size As Integer
        For Each x As ISerializable In _DataItems
            size += x.CalculateTotalSize
        Next
        Return size
    End Function

    Public Function CalculateTotalSize() As Integer Implements ISerializable.CalculateTotalSize
        Return SizeFixPart + CalculateDataSize()
    End Function

    Public ReadOnly Property FlapDataSize() As Integer Implements ISerializable.DataSize
        Get
            Return _DataSize
        End Get
    End Property

    Public ReadOnly Property FlapTotalSize() As Integer Implements ISerializable.TotalSize
        Get
            Return SizeFixPart + FlapDataSize
        End Get
    End Property

    Public Overridable Sub Deserialize(ByVal data As System.Collections.Generic.List(Of Byte)) Implements ISerializable.Deserialize
        Dim index As Integer

        index += 1

        _Channel = DirectCast(data(index), FlapChannel)
        index += 1

        _DatagramSequenceNumber = ByteConverter.ToUInt16(data.GetRange(index, 2))
        index += 2

        _DataSize = ByteConverter.ToUInt16(data.GetRange(index, 2))
        index += 2

        Select Case _Channel
            Case FlapChannel.SnacData
                Dim desc As SnacDescriptor = SnacDescriptor.GetDescriptor(index, data)
                Dim x As Snac = SerializationContext.DeserializeSnac(index, desc, data)

                Try
                    If x Is Nothing Then Throw New NotImplementedException(String.Format("Snac {0} is not implemented.", SnacDescriptor.GetKey(desc)))
                    index += x.SnacTotalSize

                    _DataItems.Add(x)

                    If index < _DataSize Then Throw New InvalidOperationException(String.Format("Deserialization of Snac {0} failed {1} bytes remaining.", SnacDescriptor.GetKey(desc), data.Count - index))
                Catch ex As Exception
                    JCsTools.Core.Kernel.Exceptions.PublishException(ex)
                End Try
            Case FlapChannel.CloseConnectionNegotiation
                Do While index < FlapDataSize
                    Dim desc As TlvDescriptor = TlvDescriptor.GetDescriptor(index, data)

                    Select Case desc.TypeId
                        Case &H1
                            Dim tlv As TlvScreenName

                            tlv = New TlvScreenName
                            tlv.Deserialize(data.GetRange(index, desc.TotalSize))

                            DataItems.Add(tlv)
                        Case &H5
                            Dim tlv As TlvBosServerAddress

                            tlv = New TlvBosServerAddress
                            tlv.Deserialize(data.GetRange(index, desc.TotalSize))

                            DataItems.Add(tlv)
                        Case &H6
                            Dim tlv As TlvAuthorizationCookie

                            tlv = New TlvAuthorizationCookie
                            tlv.Deserialize(data.GetRange(index, desc.TotalSize))

                            DataItems.Add(tlv)
                        Case &H8
                            Dim tlv As TlvAuthFailed

                            tlv = New TlvAuthFailed
                            tlv.Deserialize(data.GetRange(index, desc.TotalSize))

                            DataItems.Add(tlv)
                    End Select

                    index += desc.TotalSize
                Loop
        End Select

        _HasData = True
    End Sub

    Public Overridable Function Serialize() As System.Collections.Generic.List(Of Byte) Implements ISerializable.Serialize
        Dim data As List(Of Byte)

        _DataSize = CalculateDataSize()

        data = New List(Of Byte)(SizeFixPart + _DataSize)

        data.Add(&H2A)
        data.Add(_Channel)
        data.AddRange(ByteConverter.GetBytes(CUShort(_DatagramSequenceNumber)))

        If _DataSize > UInt16.MaxValue Then Throw New OverflowException(String.Format("DataSize cannot exceed {0} bytes", UInt32.MaxValue))

        data.AddRange(ByteConverter.GetBytes(Convert.ToUInt16(_DataSize)))

        For Each x As ISerializable In DataItems
            data.AddRange(x.Serialize)
        Next

        Return data
    End Function

End Class

Public Enum FlapChannel As Byte
    NewConnectionNegotiation = 1
    SnacData = 2
    FlapLevelError = 3
    CloseConnectionNegotiation = 4
    KeepAlive = 5
End Enum

Public Class FlapDescriptor
    Public Shared Function GetDescriptor(ByVal offset As Integer, ByVal bytes As List(Of Byte)) As FlapDescriptor
        Dim data As List(Of Byte) = bytes.GetRange(offset, bytes.Count - offset)

        Dim desc As FlapDescriptor = New FlapDescriptor
        desc.Deserialize(data)

        Return desc
    End Function

    Private Sub Deserialize(ByVal data As List(Of Byte))
        Dim index As Integer = 0

        If data(index) <> &H2A Then
            Dim info As String = Nothing

            For i As Integer = 0 To Flap.SizeFixPart - 1
                info += String.Format("{0:X} ", data(i))
            Next

            Throw New InvalidOperationException(String.Format("No flap at this position: {0}", info))
        End If

        index += 1

        _Channel = DirectCast(data(index), FlapChannel)
        index += 1

        _DatagramSequenceNumber = ByteConverter.ToUInt16(data.GetRange(index, 2))
        index += 2

        _DataSize = ByteConverter.ToUInt16(data.GetRange(index, 2))
        index += 2
    End Sub

    Private _Channel As FlapChannel
    Public Property Channel() As FlapChannel
        Get
            Return _Channel
        End Get
        Set(ByVal value As FlapChannel)
            _Channel = value
        End Set
    End Property

    Private _DatagramSequenceNumber As Integer
    Public Property DatagramSequenceNumber() As Integer
        Get
            Return _DatagramSequenceNumber
        End Get
        Set(ByVal value As Integer)
            _DatagramSequenceNumber = value
        End Set
    End Property

    Private _DataSize As Integer
    Public ReadOnly Property DataSize() As Integer
        Get
            Return _DataSize
        End Get
    End Property

    Public ReadOnly Property TotalSize() As Integer
        Get
            Return 6 + DataSize
        End Get
    End Property
End Class

Public Class TlvBosServerAddress
    Inherits Tlv

    Public Sub New()
        MyBase.New(&H5)
    End Sub

    Public Overrides Function CalculateDataSize() As Integer
        Return _BosServerAddress.Length
    End Function

    Private _BosServerAddress As String
    Public Property BosServerAddress() As String
        Get
            Return _BosServerAddress
        End Get
        Set(ByVal value As String)
            _BosServerAddress = value
        End Set
    End Property

    Public Overrides Sub Deserialize(ByVal data As System.Collections.Generic.List(Of Byte))
        MyBase.Deserialize(data)

        Dim index As Integer = Tlv.SizeFixPart

        _BosServerAddress = ByteConverter.ToString(data.GetRange(index, DataSize))
    End Sub

    Public Overrides Function Serialize() As System.Collections.Generic.List(Of Byte)
        Dim data As List(Of Byte) = MyBase.Serialize()

        data.AddRange(ByteConverter.GetBytes(_BosServerAddress))

        Return data
    End Function
End Class

Public Class TlvAuthorizationCookie
    Inherits Tlv

    Public Sub New()
        MyBase.New(&H6)
    End Sub

    Private _AuthorizationCookie As New List(Of Byte)
    Public ReadOnly Property AuthorizationCookie() As List(Of Byte)
        Get
            Return _AuthorizationCookie
        End Get
    End Property

    Public Overrides Sub Deserialize(ByVal data As System.Collections.Generic.List(Of Byte))
        MyBase.Deserialize(data)

        Dim index As Integer = Tlv.SizeFixPart

        _AuthorizationCookie.AddRange(data.GetRange(index, DataSize))
    End Sub

    Public Overrides Function Serialize() As System.Collections.Generic.List(Of Byte)
        Dim data As List(Of Byte) = MyBase.Serialize()

        data.AddRange(_AuthorizationCookie)

        Return data
    End Function

    Public Overrides Function CalculateDataSize() As Integer
        Return _AuthorizationCookie.Count
    End Function
End Class

Public Class FlapSendSignInCookie
    Inherits Flap

    Public Sub New()
        MyBase.New(FlapChannel.NewConnectionNegotiation)
    End Sub

    Public Overrides Function CalculateDataSize() As Integer
        Return 4 + _AuthorizationCookie.CalculateTotalSize
    End Function

    Private _AuthorizationCookie As New TlvAuthorizationCookie
    Public ReadOnly Property AuthorizationCookie() As TlvAuthorizationCookie
        Get
            Return _AuthorizationCookie
        End Get
    End Property

    Public Overrides Function Serialize() As System.Collections.Generic.List(Of Byte)
        Dim data As List(Of Byte) = MyBase.Serialize()

        data.AddRange(ByteConverter.GetBytes(CUInt(1)))

        data.AddRange(_AuthorizationCookie.Serialize)

        Return data
    End Function

    Public Overrides Sub Deserialize(ByVal data As System.Collections.Generic.List(Of Byte))
        Throw New NotImplementedException
    End Sub
End Class